<template>
  <div>
    <customDialog
      :title="`${title}模板库`"
      :dialogVisible="dialogVisible"
      @close="closeDialog(ruleFormRef)"
      @confirm="confirmDialog(ruleFormRef)"
      width="800"
    >
      <div>
        <el-form
          ref="ruleFormRef"
          :model="formData"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="模板名称" prop="name">
            <el-input
              v-model="formData.name"
              placeholder="请输入模板名称"
              maxlength="20"
              show-word-limit
              clearable
            />
          </el-form-item>
          <el-row>
            <el-col :span="22">
              <el-form-item class="template_box">
                <!-- 添加 -->
                <defaultTemplate ref="baseTemplateRef" />
              </el-form-item>
            </el-col>
            <el-col :span="2" v-if="cutBoard">
              <el-button type="primary" plain @click="clickPaste">
                粘 贴
              </el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </customDialog>
  </div>
</template>

<script lang="ts" setup>
import customDialog from "@/components/CustomDialog/index.vue";
import defaultTemplate from "@/components/DefaultRechargeTemlate/defaultTemlate.vue";
import { ref, reactive, toRefs, onMounted, computed } from "vue";
import {
  creatTemplates,
  updateTmplLibrary,
} from "@/api/globalManage/rechargeTemplate/index";
import { pasteBoard } from "@/utils/tools";
import type { FormInstance } from "element-plus";

const ruleFormRef = ref<FormInstance>();
const dialogVisible = ref(false);
const title = ref<string>("");
const cutBoard = ref();
const form = {
  id: "",
  name: "",
};
const formData = reactive(Object.assign({}, form));

const rules = reactive({
  name: [{ required: true, message: "请输入模板名称", trigger: "blur" }],
});

// 关闭
const closeDialog = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl?.resetFields();
  formData.name = "";
  baseTemplateRef.value.relationDtoList = [];
  dialogVisible.value = false;
};

// 成功添加 / 修改
const emit = defineEmits(["success"]);
const confirmDialog = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      let URL;
      let params = {
        id: title.value == "编辑" ? formData.id : "",
        name: formData.name,
        items: baseTemplateRef.value.relationDtoList,
      };
      if (title.value == "新增") {
        URL = creatTemplates;
      } else {
        URL = updateTmplLibrary;
      }
      URL(params).then(() => {
        dialogVisible.value = false;
        ElMessage.success("修改成功");
        emit("success");
      });
    }
  });
};

// 粘贴板内容
const clickPaste = () => {
  baseTemplateRef.value.relationDtoList = cutBoard.value || [];
};

// 父级电子显示dialog
const baseTemplateRef = ref();
const showDialog = async (val: any, text: string) => {
  // console.log("编辑模板列表----", val, text);
  dialogVisible.value = true;
  title.value = text;
  if (val) {
    formData.id = val?.id;
    formData.name = val?.name;
    nextTick(() => {
      // 防止污染数据
      baseTemplateRef.value.relationDtoList =
        JSON.parse(JSON.stringify(val?.items)) || [];
    });
  }
  // let tempBoard = (await pasteBoard()) as string;  // 剪贴板内容
  // console.log("tempBoard ----- ", tempBoard);
  // if (tempBoard && Array.isArray(JSON.parse(tempBoard))) {
  //   cutBoard.value = tempBoard ? JSON.parse(tempBoard) : ""; // 赋值剪贴板内容
  // } else {
  //   cutBoard.value = "";
  // }
  let temp = JSON.parse(localStorage.getItem("copyTemp") as string) || "";
  if (temp && Array.isArray(temp)) {
    cutBoard.value = temp; // 赋值剪切板内容
  } else {
    cutBoard.value = "";
  }
  console.log("board ----- ", cutBoard.value);
};

defineExpose({
  showDialog,
});
</script>

<style scoped lang="scss">
.template_box {
  :deep(.el-form-item) {
    margin-bottom: 18px;
  }
}
</style>
